package com.ruoyi.common.qy.utils;

import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 解析各种链接的工具类
 */
public class ExtreUtls {
    // 更精确的小红书链接匹配
    private static final Pattern XIAOHONGSHU_SPECIFIC_PATTERN = Pattern.compile(
            "(https?://(?:www\\.)?xiaohongshu\\.com/discovery/item/[^\\s]+)"
    );
    // 匹配小红书短链接
    private static final Pattern XHS_SHORT_PATTERN = Pattern.compile(
            "(https?://xhslink\\.com/[^\\s]+)"
    );
    // 通用链接匹配作为后备
    private static final Pattern LINK_PATTERN = Pattern.compile(
            "(https?://[^\\s]+)"
    );

    /**
     * 从小红书分享文本中提取链接（主要方法）
     * 格式：文本内容 https://www.xiaohongshu.com/discovery/item/xxx?params 复制此链接...
     * 或：文本内容 https://xhslink.com/xxx 复制此链接...
     */
    public static Optional<String> extractLinkXiaoHongShu(String shareText) {
        if (shareText == null || shareText.trim().isEmpty()) {
            return Optional.empty();
        }

        // 先尝试精确匹配小红书长链接
        Matcher matcher = XIAOHONGSHU_SPECIFIC_PATTERN.matcher(shareText);
        if (matcher.find()) {
            return Optional.of(matcher.group(1).trim());
        }

        // 再尝试匹配小红书短链接
        matcher = XHS_SHORT_PATTERN.matcher(shareText);
        if (matcher.find()) {
            return Optional.of(matcher.group(1).trim());
        }

        // 如果精确匹配失败，使用通用匹配作为后备
        matcher = LINK_PATTERN.matcher(shareText);
        if (matcher.find()) {
            String url = matcher.group(1).trim();
            // 额外检查是否包含小红书相关关键词
            if (url.contains("xiaohongshu") || url.contains("xhslink")) {
                return Optional.of(url);
            }
        }

        return Optional.empty();
    }
}
